package com.office.workflow.service.impl;

import com.office.common.utils.DateUtils;
import com.office.common.utils.SecurityUtils;
import com.office.common.utils.StringUtils;
import com.office.common.utils.uuid.Seq;
import com.office.workflow.domain.Workflow;
import com.office.workflow.domain.WorkflowNode;
import com.office.workflow.domain.WorkflowLink;
import com.office.workflow.domain.WorkflowInstance;
import com.office.workflow.mapper.WorkflowMapper;
import com.office.workflow.service.WorkflowService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 工作流Service业务层处理
 * 
 * @author 数字牧马人
 */
@Service
public class WorkflowServiceImpl implements WorkflowService 
{
    @Autowired
    private WorkflowMapper workflowMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询工作流列表
     * 
     * @param workflow 工作流
     * @return 工作流
     */
    @Override
    public List<Workflow> selectWorkflowList(Workflow workflow)
    {
        List<Workflow> list = workflowMapper.selectWorkflowList(workflow);
        // 统计每个工作流的执行次数
        for (Workflow wf : list) {
            int count = workflowMapper.countWorkflowExecutions(wf.getId());
            wf.setExecutionCount(count);
        }
        return list;
    }

    /**
     * 查询工作流
     * 
     * @param id 工作流主键
     * @return 工作流
     */
    @Override
    public Workflow selectWorkflowById(Long id)
    {
        return workflowMapper.selectWorkflowById(id);
    }

    /**
     * 新增工作流
     * 
     * @param workflow 工作流
     * @return 结果
     */
    @Override
    public int insertWorkflow(Workflow workflow)
    {
        workflow.setCreateTime(DateUtils.getNowDate());
        workflow.setCreateBy(SecurityUtils.getUsername());
        if (StringUtils.isEmpty(workflow.getVersion())) {
            workflow.setVersion("1.0");
        }
        if (StringUtils.isEmpty(workflow.getStatus())) {
            workflow.setStatus("0");
        }
        return workflowMapper.insertWorkflow(workflow);
    }

    /**
     * 修改工作流
     * 
     * @param workflow 工作流
     * @return 结果
     */
    @Override
    public int updateWorkflow(Workflow workflow)
    {
        workflow.setUpdateTime(DateUtils.getNowDate());
        workflow.setUpdateBy(SecurityUtils.getUsername());
        return workflowMapper.updateWorkflow(workflow);
    }

    /**
     * 批量删除工作流
     * 
     * @param ids 需要删除的工作流主键
     * @return 结果
     */
    @Override
    public int deleteWorkflowByIds(Long[] ids)
    {
        return workflowMapper.deleteWorkflowByIds(ids);
    }

    /**
     * 删除工作流信息
     * 
     * @param id 工作流主键
     * @return 结果
     */
    @Override
    public int deleteWorkflowById(Long id)
    {
        return workflowMapper.deleteWorkflowById(id);
    }

    /**
     * 保存工作流设计（包含节点和连线）
     * 
     * @param workflow 工作流
     * @return 结果
     */
    @Override
    @Transactional
    public int saveWorkflowDesign(Workflow workflow)
    {
        // 更新工作流基本信息
        workflow.setUpdateTime(DateUtils.getNowDate());
        workflow.setUpdateBy(SecurityUtils.getUsername());
        int result = workflowMapper.updateWorkflow(workflow);

        // 删除原有的节点和连线
        workflowMapper.deleteWorkflowNodesByWorkflowId(workflow.getId());
        workflowMapper.deleteWorkflowLinksByWorkflowId(workflow.getId());

        // 保存节点
        if (workflow.getNodes() != null && !workflow.getNodes().isEmpty()) {
            List<WorkflowNode> nodes = new ArrayList<>();
            for (int i = 0; i < workflow.getNodes().size(); i++) {
                WorkflowNode node = workflow.getNodes().get(i);
                node.setWorkflowId(workflow.getId());
                node.setSortOrder(i);
                node.setCreateTime(DateUtils.getNowDate());
                node.setUpdateTime(DateUtils.getNowDate());
                
                // 处理配置JSON
                if (node.getConfig() != null && !(node.getConfig() instanceof String)) {
                    try {
                        node.setConfig(objectMapper.writeValueAsString(node.getConfig()));
                    } catch (Exception e) {
                        // 忽略JSON序列化错误
                    }
                }
                nodes.add(node);
            }
            workflowMapper.batchInsertWorkflowNodes(nodes);
        }

        // 保存连线
        if (workflow.getLinks() != null && !workflow.getLinks().isEmpty()) {
            List<WorkflowLink> links = new ArrayList<>();
            for (WorkflowLink link : workflow.getLinks()) {
                link.setWorkflowId(workflow.getId());
                link.setCreateTime(DateUtils.getNowDate());
                link.setUpdateTime(DateUtils.getNowDate());
                
                // 处理属性JSON
                if (link.getAttr() != null && !(link.getAttr() instanceof String)) {
                    try {
                        link.setAttr(objectMapper.writeValueAsString(link.getAttr()));
                    } catch (Exception e) {
                        // 忽略JSON序列化错误
                    }
                }
                links.add(link);
            }
            workflowMapper.batchInsertWorkflowLinks(links);
        }

        return result;
    }

    /**
     * 获取工作流设计数据
     * 
     * @param id 工作流ID
     * @return 工作流设计数据
     */
    @Override
    public Workflow getWorkflowDesign(Long id)
    {
        Workflow workflow = workflowMapper.selectWorkflowById(id);
        if (workflow != null) {
            // 获取节点
            List<WorkflowNode> nodes = workflowMapper.selectWorkflowNodesByWorkflowId(id);
            workflow.setNodes(nodes);

            // 获取连线
            List<WorkflowLink> links = workflowMapper.selectWorkflowLinksByWorkflowId(id);
            workflow.setLinks(links);
        }
        return workflow;
    }

    /**
     * 执行工作流
     * 
     * @param workflowId 工作流ID
     * @param inputParams 输入参数
     * @return 执行结果
     */
    @Override
    public Map<String, Object> executeWorkflow(Long workflowId, Map<String, Object> inputParams)
    {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建执行实例
            WorkflowInstance instance = new WorkflowInstance();
            instance.setWorkflowId(workflowId);
            instance.setInstanceId("INST_" + Seq.getId());
            instance.setName("工作流执行实例_" + DateUtils.getTime());
            instance.setStatus("0"); // 运行中
            instance.setInputParams(objectMapper.writeValueAsString(inputParams));
            instance.setStartTime(DateUtils.getNowDate());
            instance.setCreateBy(SecurityUtils.getUsername());
            instance.setCreateTime(DateUtils.getNowDate());
            
            workflowMapper.insertWorkflowInstance(instance);

            // 获取工作流设计
            Workflow workflow = getWorkflowDesign(workflowId);
            if (workflow == null || workflow.getNodes() == null || workflow.getNodes().isEmpty()) {
                throw new RuntimeException("工作流不存在或没有节点");
            }

            // 执行工作流逻辑（这里简化处理，实际应该根据节点类型执行相应的逻辑）
            Map<String, Object> outputResult = new HashMap<>();
            outputResult.put("success", true);
            outputResult.put("message", "工作流执行成功");
            outputResult.put("data", inputParams);

            // 更新实例状态
            instance.setStatus("1"); // 已完成
            instance.setOutputResult(objectMapper.writeValueAsString(outputResult));
            instance.setEndTime(DateUtils.getNowDate());
            instance.setDuration(System.currentTimeMillis() - instance.getStartTime().getTime());
            instance.setUpdateTime(DateUtils.getNowDate());
            
            workflowMapper.updateWorkflowInstance(instance);

            result.put("success", true);
            result.put("instanceId", instance.getInstanceId());
            result.put("output", outputResult);

        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
        }

        return result;
    }

    /**
     * 查询工作流执行实例列表
     * 
     * @param instance 实例
     * @return 实例集合
     */
    @Override
    public List<WorkflowInstance> selectWorkflowInstanceList(WorkflowInstance instance)
    {
        return workflowMapper.selectWorkflowInstanceList(instance);
    }

    /**
     * 查询工作流执行实例
     * 
     * @param id 实例主键
     * @return 实例
     */
    @Override
    public WorkflowInstance selectWorkflowInstanceById(Long id)
    {
        return workflowMapper.selectWorkflowInstanceById(id);
    }

    /**
     * 删除工作流执行实例
     * 
     * @param id 实例主键
     * @return 结果
     */
    @Override
    public int deleteWorkflowInstanceById(Long id)
    {
        return workflowMapper.deleteWorkflowInstanceById(id);
    }

    /**
     * 批量删除工作流执行实例
     * 
     * @param ids 需要删除的实例主键
     * @return 结果
     */
    @Override
    public int deleteWorkflowInstanceByIds(Long[] ids)
    {
        return workflowMapper.deleteWorkflowInstanceByIds(ids);
    }

    /**
     * 导入工作流
     * 
     * @param workflowData 工作流数据
     * @return 结果
     */
    @Override
    @Transactional
    public int importWorkflow(Map<String, Object> workflowData)
    {
        try {
            // 创建工作流
            Workflow workflow = new Workflow();
            workflow.setName((String) workflowData.get("name"));
            workflow.setEname((String) workflowData.get("ename"));
            workflow.setDesc((String) workflowData.get("desc"));
            workflow.setIcon((String) workflowData.get("icon"));
            workflow.setVersion((String) workflowData.get("version"));
            workflow.setStatus("0"); // 草稿状态
            workflow.setCategory((String) workflowData.get("category"));
            
            int result = insertWorkflow(workflow);

            // 导入节点和连线
            if (result > 0) {
                // 处理节点
                List<Map<String, Object>> nodesData = (List<Map<String, Object>>) workflowData.get("nodes");
                if (nodesData != null) {
                    List<WorkflowNode> nodes = new ArrayList<>();
                    for (int i = 0; i < nodesData.size(); i++) {
                        Map<String, Object> nodeData = nodesData.get(i);
                        WorkflowNode node = new WorkflowNode();
                        node.setWorkflowId(workflow.getId());
                        node.setNodeId((String) nodeData.get("id"));
                        node.setName((String) nodeData.get("name"));
                        node.setType((String) nodeData.get("type"));
                        node.setDesc((String) nodeData.get("desc"));
                        node.setX((Integer) nodeData.get("x"));
                        node.setY((Integer) nodeData.get("y"));
                        node.setAsync((Boolean) nodeData.get("async"));
                        node.setLoop((Boolean) nodeData.get("loop"));
                        node.setSortOrder(i);
                        node.setCreateTime(DateUtils.getNowDate());
                        node.setUpdateTime(DateUtils.getNowDate());
                        
                        // 处理配置
                        Object config = nodeData.get("config");
                        if (config != null) {
                            node.setConfig(objectMapper.writeValueAsString(config));
                        }
                        
                        nodes.add(node);
                    }
                    workflowMapper.batchInsertWorkflowNodes(nodes);
                }

                // 处理连线
                List<Map<String, Object>> linksData = (List<Map<String, Object>>) workflowData.get("links");
                if (linksData != null) {
                    List<WorkflowLink> links = new ArrayList<>();
                    for (Map<String, Object> linkData : linksData) {
                        WorkflowLink link = new WorkflowLink();
                        link.setWorkflowId(workflow.getId());
                        link.setLinkId((String) linkData.get("id"));
                        link.setFromNodeId((String) linkData.get("from"));
                        link.setToNodeId((String) linkData.get("to"));
                        link.setCondition((String) linkData.get("condition"));
                        link.setCreateTime(DateUtils.getNowDate());
                        link.setUpdateTime(DateUtils.getNowDate());
                        
                        // 处理属性
                        Object attr = linkData.get("attr");
                        if (attr != null) {
                            link.setAttr(objectMapper.writeValueAsString(attr));
                        }
                        
                        links.add(link);
                    }
                    workflowMapper.batchInsertWorkflowLinks(links);
                }
            }

            return result;
        } catch (Exception e) {
            throw new RuntimeException("导入工作流失败: " + e.getMessage());
        }
    }

    /**
     * 导出工作流
     * 
     * @param id 工作流ID
     * @return 工作流数据
     */
    @Override
    public Map<String, Object> exportWorkflow(Long id)
    {
        Workflow workflow = getWorkflowDesign(id);
        if (workflow == null) {
            throw new RuntimeException("工作流不存在");
        }

        Map<String, Object> exportData = new HashMap<>();
        exportData.put("name", workflow.getName());
        exportData.put("ename", workflow.getEname());
        exportData.put("desc", workflow.getDesc());
        exportData.put("icon", workflow.getIcon());
        exportData.put("version", workflow.getVersion());
        exportData.put("category", workflow.getCategory());
        exportData.put("tags", workflow.getTags());

        // 导出节点
        List<Map<String, Object>> nodesData = new ArrayList<>();
        if (workflow.getNodes() != null) {
            for (WorkflowNode node : workflow.getNodes()) {
                Map<String, Object> nodeData = new HashMap<>();
                nodeData.put("id", node.getNodeId());
                nodeData.put("name", node.getName());
                nodeData.put("type", node.getType());
                nodeData.put("desc", node.getDesc());
                nodeData.put("x", node.getX());
                nodeData.put("y", node.getY());
                nodeData.put("async", node.getAsync());
                nodeData.put("loop", node.getLoop());
                
                // 处理配置
                if (StringUtils.isNotEmpty(node.getConfig())) {
                    try {
                        nodeData.put("config", objectMapper.readValue(node.getConfig(), Object.class));
                    } catch (Exception e) {
                        nodeData.put("config", node.getConfig());
                    }
                }
                
                nodesData.add(nodeData);
            }
        }
        exportData.put("nodes", nodesData);

        // 导出连线
        List<Map<String, Object>> linksData = new ArrayList<>();
        if (workflow.getLinks() != null) {
            for (WorkflowLink link : workflow.getLinks()) {
                Map<String, Object> linkData = new HashMap<>();
                linkData.put("id", link.getLinkId());
                linkData.put("from", link.getFromNodeId());
                linkData.put("to", link.getToNodeId());
                linkData.put("condition", link.getCondition());
                linkData.put("conditionDesc", link.getConditionDesc());
                
                // 处理属性
                if (StringUtils.isNotEmpty(link.getAttr())) {
                    try {
                        linkData.put("attr", objectMapper.readValue(link.getAttr(), Object.class));
                    } catch (Exception e) {
                        linkData.put("attr", link.getAttr());
                    }
                }
                
                linksData.add(linkData);
            }
        }
        exportData.put("links", linksData);

        return exportData;
    }
} 